package com.leo.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @ClassName FirstServerHandler
 * @Description
 * @Author wangss
 * @date 2022.03.21 20:24
 * @Version 1.0
 */
public class FirstServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        System.out.println(new Date() + ": 服务端读到数据 -> " + byteBuf.toString(StandardCharsets.UTF_8));

        System.out.println(new Date() + " 服务端写出数据");
        ByteBuf byteBuf1 = getByteBuf(ctx);
        ctx.channel().writeAndFlush(byteBuf1);
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        // 1.获取二进制抽象 byteBuf
        ByteBuf buffer = ctx.alloc().buffer();

        // 2.准备数据，指定字符串的字符集为utf-8
        byte[] bytes = "你好，我是来自服务端的我".getBytes(StandardCharsets.UTF_8);

        // 3.填充数据到byteBuf
        buffer.writeBytes(bytes);

        return buffer;
    }
}
